package vader.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by kunsir on 2019/11/25.
 */
@Slf4j
public class HttpUtils {

    public static ResponseEntity<String> sendGet(String url, Map<String, String> headers, String charset) throws Exception {

        RestTemplate restTemplate = new RestTemplate();
        if (StringUtils.isNotEmpty(charset)) {
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName(charset)));
        }
        restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() {
            @Override
            public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
                if (headers != null) {
                    for (String header : headers.keySet()) {
                        request.getHeaders().set(header, headers.get(header));
                    }
                }
                return execution.execute(request, body);
            }
        });
        ResponseEntity<String> response = restTemplate.getForEntity(new URI(url), String.class);
        return response;
    }

    public static ResponseEntity<String> sendGet(String url, Map<String, String> headers, String charset, Integer connectTimeout) throws Exception {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(connectTimeout);// 设置超时
        requestFactory.setReadTimeout(connectTimeout);
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        if (StringUtils.isNotEmpty(charset)) {
            restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName(charset)));
        }
        restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() {
            @Override
            public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
                if (headers != null) {
                    for (String header : headers.keySet()) {
                        request.getHeaders().set(header, headers.get(header));
                    }
                }
                return execution.execute(request, body);
            }
        });
        ResponseEntity<String> response = restTemplate.getForEntity(new URI(url), String.class);
        return response;
    }

    public static Map<String, String> sendPost(String url, Map<String, String> params, Map<String, String> headers) {
        log.info("post:" + url);
        try {
            HttpHeaders httpHeaders = new HttpHeaders();
            for (String header : headers.keySet()) {
                httpHeaders.set(header, headers.get(header));
            }
            httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);


            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
            for (String param : params.keySet()) {
                log.info("param:" + param + "," + params.get(param));
                map.add(param, params.get(param));
            }

            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, httpHeaders);

            RestTemplate rest = new RestTemplate();
            ResponseEntity<String> entity = rest.postForEntity(new URI(url), request, String.class);

            Map<String, String> resultMap = new HashMap<String, String>();
            String result = entity.getBody();
            if (entity.getHeaders().containsKey("set-cookie")) {
                String cookie = (String) (entity.getHeaders().get("set-cookie").get(0));
                resultMap.put("cookie", cookie);
            }

            resultMap.put("result", result);
            return resultMap;
        } catch (Exception e) {
            log.error("send post error:", e);
            return null;
        }
    }

}
